# src/infrastructure/logger.py
import logging
import sys


def setupLogger(name: str, level: str = "INFO") -> logging.Logger:
    """
    创建并配置带彩色输出的日志记录器

    Args:
        name (str): 日志记录器名称
        level (str): 日志级别, 如"INFO"、"DEBUG"等, 默认为"INFO"
    Return:
        logging.Logger: 配置好的日志记录器对象
    """

    class ColorFormatter(logging.Formatter):
        COLORS = {
            "DEBUG": "\033[36m",  # 青色
            "INFO": "\033[32m",  # 绿色
            "WARNING": "\033[33m",  # 黄色
            "ERROR": "\033[31m",  # 红色
            "CRITICAL": "\033[41m",  # 红底
        }
        RESET = "\033[0m"

        def format(self, record):
            color = self.COLORS.get(record.levelname, "")
            created = self.formatTime(record, self.datefmt)
            header = f"{created} - {record.name} - {record.levelname}"
            return f"{color}{header}{self.RESET} - {record.getMessage()}"

    logger = logging.getLogger(name)
    logger.setLevel(getattr(logging, level.upper()))

    # 确保只添加一次 Handler
    if not logger.hasHandlers():
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(
            ColorFormatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        )
        logger.addHandler(handler)
        # 让子树日志能冒到 root 被统一打印
        # if name != "root":
        #     logger.propagate = False

    return logger
